package cn.edu.sdjzu.xg.kcsj.controller.authority;

import cn.edu.sdjzu.xg.kcsj.exception.BysjException;
import cn.edu.sdjzu.xg.kcsj.security.User;
import cn.edu.sdjzu.xg.kcsj.security.UserService;
import cn.edu.sdjzu.xg.kcsj.util.Condition;
import cn.edu.sdjzu.xg.kcsj.util.ControllerHelper;
import cn.edu.sdjzu.xg.kcsj.util.JSONUtil;
import cn.edu.sdjzu.xg.kcsj.util.Pagination;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

@WebServlet("/userFindAll")
public class UserFindAllController extends HttpServlet {
    // 记录器，可以控制日志信息输出到控制台，替代输出语句
    private static final Logger log = LogManager.getLogger(UserFindAllController.class);

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        JSONObject message = new JSONObject();
        // 如果请求body为空
        if (request == null) {
            log.debug("未收到请求信息！");
            message.put("message","未收到请求信息！");
            response.getWriter().println(message);
            return;
        }
        try {
            // 将request body转换为JSON字串
            String req_jsonStr = JSONUtil.getJSON(request);
            // 将request body解析为JSONObject对象
            JSONObject req_jsonObj = JSON.parseObject(req_jsonStr);
            // 从JSONObject对象中读取 “pagination” 键对应的值(JSONObject对象)
            Pagination pagination = ControllerHelper.getPagination(req_jsonObj);
            // 从请求JSONObject对象中读取键“conditionList”对应的值(描述查询条件的JSONArray对象)
            List<Condition> conditionList = ControllerHelper.getConditions(req_jsonObj);
            Collection<User> users = UserService.getInstance().findAll(conditionList,pagination);
            message.put("totalNum", pagination.getTotalNum());
            message.put("totalPages",pagination.getTotalPages(pagination));
            message.put("data", users);
            // 响应resp_jsonObj到前端
            response.getWriter().println(message);
        } catch (BysjException e) {
            message.put("message", e.getMessage());
            response.getWriter().println(message);
            // 在命令行打印异常信息在程序中出错的位置及原因
            e.printStackTrace();
        } catch (SQLException e) {
            message.put("message", "数据库操作异常");
            response.getWriter().println(message);
            // 在命令行打印异常信息在程序中出错的位置及原因
            e.printStackTrace();
        } catch (Exception e) {
            message.put("message", "网络异常");
            response.getWriter().println(message);
            // 在命令行打印异常信息在程序中出错的位置及原因
            e.printStackTrace();
        }
    }
}
